﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Drawing;
using SGP;

namespace Sprite_Editor
{
    class ParticlePreview
    {
        public ParticlePreview(Emitter emitter)
        {
            this.emitter = emitter;
        }

        public void Initialize()
        {
            Random random = new Random(DateTime.Now.Millisecond);

            curcolor = emitter.InitialColor;
            startcolor = emitter.InitialColor;
            currotation = (float)(emitter.InitialRotation * Math.PI / 180);
            curscale = emitter.InitialScale;

            rotationperupdate = (float)(((emitter.FinalRotation * Math.PI / 180) - (emitter.InitialRotation * Math.PI / 180)) / lifetime);
            scalechangeperupdate = (emitter.FinalScale - emitter.InitialScale) / lifetime;

            timealive = 0.0f;
            lifetime = (emitter.LifetimeMin + emitter.LifetimeMax) / 2;
        }

        public void Update(float deltaTime)
        {
            timealive += deltaTime;

            if (timealive > lifetime)
            {
                this.Initialize();
            }
            else
            {
                curscale += scalechangeperupdate * deltaTime;
                currotation += rotationperupdate * deltaTime;

                int aval = (int)(startcolor.A + ((emitter.FinalColor.A - startcolor.A) * (timealive / lifetime)));
                int rval = (int)(startcolor.R + ((emitter.FinalColor.R - startcolor.R) * (timealive / lifetime)));
                int gval = (int)(startcolor.G + ((emitter.FinalColor.G - startcolor.G) * (timealive / lifetime)));
                int bval = (int)(startcolor.B + ((emitter.FinalColor.B - startcolor.B) * (timealive / lifetime)));

                curcolor = Color.FromArgb(aval, rval, gval, bval);
            }
        }

        public void Render()
        {
            CSGP_TextureManager.GetInstance().Draw(TextureInfo.ID, (int)(posX - (TextureInfo.Width / 2)), (int)(posY - (TextureInfo.Height / 2)), curscale, curscale, new Rectangle(0, 0, TextureInfo.Width, TextureInfo.Height), TextureInfo.Width * curscale / 2, TextureInfo.Height * curscale / 2, currotation, curcolor);
        }

        private float posX;

        public float PosX
        {
            get { return posX; }
            set { posX = value; }
        }

        private float posY;

        public float PosY
        {
            get { return posY; }
            set { posY = value; }
        }

        private float timealive;
        private Color curcolor;
        private Color startcolor;
        private float lifetime;
        private float currotation;
        private float curscale;
        private float rotationperupdate;
        private float scalechangeperupdate;

        private Emitter emitter;
    }
}
